package cn.fancylab.template.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.fancylab.model.acl.User;
import cn.fancylab.template.util.WebUtils;
import cn.fancylab.util.StringUtil;
import cn.fancylab.web.support.FancyMultipartResolver;
import redis.clients.jedis.JedisShardInfo;

@Controller
public class TestController extends AnnotationController {
	@RequestMapping("/test/plainResponse.xhtml")
	@ResponseBody
	public String directResponse() {
		return "I am a plain body";
	}

	@RequestMapping("/test/jsonMap.xhtml")
	public String jsonMap(String username) {
		Map jsonMap = new HashMap();
		jsonMap.put("username", username);
		return jsonSuccessReturn(jsonMap);
	}

	@RequestMapping("/test/jsonObject.xhtml")
	public String jsonObject(String username) {
		User user = new User();
		user.setNickname(username);
		return jsonSuccessReturn(user);
	}

	@RequestMapping("/test/uploadFile.xhtml")
	public String uploadFile(HttpServletRequest request) throws Exception {
		try {
			MultipartHttpServletRequest req = new FancyMultipartResolver().resolveMultipart(request);
			Map<String, String> params = WebUtils.getRequestMap(req);
			MultiValueMap<String, MultipartFile> fileMap = req.getMultiFileMap();
			List<String> list = new ArrayList<>();
			for (String fileName : fileMap.keySet()) {
				List<MultipartFile> values = fileMap.get(fileName);
				for (MultipartFile multipartFile : values) {
					File save = File.createTempFile("upload", StringUtil.getFilenameExtension(fileName));
					list.add(fileName + "---->" + save.getName());
					FileOutputStream output = new FileOutputStream(save);
					IOUtils.copy(multipartFile.getInputStream(), output);
					output.flush();
					output.close();
				}
			}
			params.put("files:", "" + list);
			return jsonSuccessReturn(params);
		} catch (Exception e) {
			dbLogger.error("出错了", e);
			return jsonErrorMsg(e.getMessage());
		}
	}

	public static void main(String[] args) {
		JedisShardInfo jedisShardInfo = new JedisShardInfo("jredis://:eboo@192.168.3.146:6379");
		System.out.println(jedisShardInfo.getHost());
		System.out.println(jedisShardInfo.getPort());
		System.out.println(jedisShardInfo.getPassword());
	}
}